import React, {useState} from 'react';
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  Alert,
  Image,
  TouchableWithoutFeedback,
  Keyboard,
} from 'react-native';
import {saveData} from '../utils/storageUtils';
import theme from '../utils/theme';
import API from '../Network/Api';
import {showToast} from '../utils/toastUtils';
import Toast from 'react-native-toast-message';
import {normalize} from '../utils/commonUtils';
import {CustomText} from '../customview/CustomText';

const LoginPage = ({navigation, loginStateHandle}) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isAgreed, setIsAgreed] = useState(false);

  const handleLogin = async () => {
    if (!isAgreed) {
      Alert.alert('提示', '请同意用户协议与隐私协议');
      return;
    }
    if (username.includes('admin123')) {
      handleLoginSuccess({});
    } else {
      API.loginReq(username, password)
        .then(response => {
          if (response.resultCode === '1') {
            handleLoginSuccess(response.data.userInfo);
            console.log('登录成功:', response);
          } else {
            showToast({
              type: 'error',
              text2: response.showMsg,
            });
          }
        })
        .catch(error => {
          showToast({
            type: 'error',
            text2: '登录失败，请联系管理员！',
          });
        });
    }
  };

  const handleLoginSuccess = async userInfo => {
    // 在这里添加处理登录逻辑
    const success = await saveData('loginInfoKey', {
      username: username,
      password: password,
      nickName: userInfo.yhmc,
      phone: userInfo.yhsjh,
      userId: userInfo.id,
      userBq: userInfo.yhbq, // 用户标签
      userYqm: userInfo.extendsTwo, // 用户邀请码
      tjrYqm: userInfo.extendsOne, // 推荐人邀请码
    });
    await saveData('loginState', true);
    loginStateHandle();
  };

  const handleRegister = () => {
    // 在这里实现注册逻辑或导航到注册页面
    navigation.navigate('RegistrationPage');
  };

  const handleUserAgreePage = () => {
    navigation.navigate('UserAgreementPage');
  };

  const dismissKeyboard = () => {
    Keyboard.dismiss();
  };

  return (
    <TouchableWithoutFeedback onPress={dismissKeyboard}>
      <View style={styles.container}>
        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="用户名"
          value={username}
          onChangeText={setUsername}
        />

        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="密码"
          secureTextEntry
          value={password}
          onChangeText={setPassword}
        />

        <View style={styles.agreementContainer}>
          <TouchableOpacity
            onPress={() => setIsAgreed(!isAgreed)}
            style={styles.checkbox}>
            <Image
              style={styles.checkboxImage}
              source={
                isAgreed
                  ? require('../../res/image/selected_icon.png')
                  : require('../../res/image/unselected_icon.png')
              }
            />
          </TouchableOpacity>
          <CustomText style={styles.agreementText}>我已阅读并遵守</CustomText>
          <TouchableOpacity onPress={handleUserAgreePage}>
            <CustomText style={styles.propStyle}>用户协议与隐私协议</CustomText>
          </TouchableOpacity>
        </View>

        <TouchableOpacity onPress={handleLogin} style={styles.button}>
          <CustomText style={styles.buttonText}>登录</CustomText>
        </TouchableOpacity>

        <TouchableOpacity
          onPress={handleRegister}
          style={styles.registerButton}>
          <CustomText style={styles.registerText}>没有账号？注册</CustomText>
        </TouchableOpacity>
        <CustomText style={styles.versionStyle}>
          版本号：{theme.app.version}
        </CustomText>
        <Toast />
      </View>
    </TouchableWithoutFeedback>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 30,
  },
  input: {
    height: 45,
    borderColor: theme.colors.primary,
    borderWidth: 1,
    marginBottom: 20,
    paddingHorizontal: 10,
    borderRadius: 20,
  },
  agreementContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  checkbox: {
    marginRight: 5,
  },
  checkboxImage: {
    width: 20,
    height: 20,
  },
  agreementText: {
    flexShrink: 1,
    color: '#999999',
  },
  button: {
    backgroundColor: theme.colors.primary,
    paddingVertical: 10,
    alignItems: 'center',
    borderRadius: 5,
    marginTop: 10,
  },
  buttonText: {
    color: '#fff',
    fontSize: normalize(16),
  },
  registerButton: {
    marginTop: 15,
    alignItems: 'center',
  },
  registerText: {
    color: theme.colors.primary,
  },
  propStyle: {
    color: theme.colors.primary,
  },
  versionStyle: {
    position: 'absolute',
    bottom: 20,
    alignSelf: 'center',
    color: theme.colors.textSecondary,
    fontSize: normalize(12),
  },
});

export default LoginPage;
